package com.ruoyi.framework.config;

import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.List;

/**
 * @author wangxianl
 * createTime: 2022/9/2.
 * description: 跨域设置
 */
@Setter
@Configuration
@ConfigurationProperties(prefix = "cors")
public class CORSConfig {

    /**
     * cookie是否发生
     */
    private Boolean allowCredentials;
    
    private Long maxAge;

    /**
     * 允许的请求
     */
    private String pattern;

    /**
     * 设置跨域源
     */
    private List<String> allowedOriginPatterns;

    /**
     * 允许的请求头
     */
    private List<String> allowHeaders;

    /**
     * 允许的方法
     */
    private List<String> allowMethods;

    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(allowCredentials);
        // 设置访问源地址
        for (String o : allowedOriginPatterns) {
            config.addAllowedOriginPattern(o);
        }

        // 设置访问源请求头
        for (String allowHeader : allowHeaders) {
            config.addAllowedHeader(allowHeader);
        }

        // 设置访问源请求方法
        for (String allowMethod : allowMethods) {
            config.addAllowedMethod(allowMethod);
        }

        // 有效期 1800秒
        config.setMaxAge(maxAge);

        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(pattern, config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }
}
